package chagine.mdt.listener;

import chagine.core.log.OplogManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.ResolvableType;

/**
 * create by wba on  2020/5/16
 * qq:43585061
 */
@Slf4j
public class OplogListener implements GenericApplicationListener {

    public static final String SERVER_CODE = "mdt";
    public static final String METHOD_GET = "GET";
    public static final String METHOD_POST = "POST";

    public static final int ORDER = 100;

    private static final Class<?>[] EVENT_TYPES = {ApplicationEnvironmentPreparedEvent.class};

    private static final Class<?>[] SOURCE_TYPES = {SpringApplication.class, ApplicationContext.class};

    @Override
    public boolean supportsEventType(ResolvableType resolvableType) {
        return isAssignableFrom(resolvableType.getRawClass(), EVENT_TYPES);
    }

    @Override
    public boolean supportsSourceType(Class<?> sourceType) {
        return isAssignableFrom(sourceType, SOURCE_TYPES);
    }

    private boolean isAssignableFrom(Class<?> type, Class<?>... supportedTypes) {
        if (type != null) {
            for (Class<?> supportedType : supportedTypes) {
                if (supportedType.isAssignableFrom(type)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        //log.info("========1OplogListener======onApplicationEvent=======================ApplicationEnvironmentPreparedEvent=========================");
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            log.info("========OplogListener======onApplicationEvent=======================ApplicationEnvironmentPreparedEvent=========================");
            OplogManager.setServerCode(SERVER_CODE);
        }

    }

    public int getOrder() {
        return ORDER;
    }
}
